//
//  PVDSignagtureViewController.swift
//  ezyform
//
//  Created by MoennigQ on 17/5/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//  用于老协议（2022-04-01之前安装的job）的四个签名：Installer,designer,owner,witness(owner的witness)

import UIKit
import AVFoundation
import MBProgressHUD
import CoreLocation
class PVDSignagtureViewController: BaseViewController {
    var model: PVDDetailModel!
    let customView = PVDSignagtureView()
    var signatureType: SignatureType!
    //for installer
    var installerTermsSelfiData: Data?
    //前置摄像头拍照
    var session: AVCaptureSession?
    var output: AVCapturePhotoOutput?
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        self.initUI()
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .authorized && (self.signatureType == .Installer || self.signatureType == .Owner){ /****已授权，可以打开相机且installer或owner才自拍****/
            setupInputOutput()
        }
        if self.signatureType == .Installer {
            Tool().requestCurrentLocation()
        }
    }
    func initUI(){
        //title
        self.view = self.customView
        self.customView.setTitleInfo(self.signatureType.rawValue + " Signature")
        self.customView.setData(self.model, signType: self.signatureType)
        
        self.customView.saveBtn.addTarget(self, action: #selector(saveBtnClick), for: UIControl.Event.touchUpInside)
        self.customView.signedTextfield.textField.delegate = self
    }
    //Get the device (Front or Back)
    func getDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: position)
        let devices = deviceDiscoverySession.devices
        if devices.count > 0 {
            return devices[0]
        }
        return nil
    }
    func setupInputOutput(){
        if let camera = getDevice(position: .front) {
            do {
                self.session = AVCaptureSession()
                self.output = AVCapturePhotoOutput()
                guard let _ = self.session,let _ = output  else {
                    return
                }
                self.session!.beginConfiguration()
                //如果session包括AVCapturePhotoOutput对象，session会自动尝试启用wide-color，有些设备(iPad)并不支持activeFormat.supportedColorSpaces，这是个AVCaptureSession的坑
                self.session!.automaticallyConfiguresCaptureDeviceForWideColor = false
                let input = try AVCaptureDeviceInput(device: camera)
                if self.session!.canAddInput(input){
                    self.session!.addInput(input)
                }
                
                output!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg] )], completionHandler: nil)
                session!.sessionPreset = .photo
                if session!.canAddOutput(output!){
                    session!.addOutput(output!)
                }
                self.session!.commitConfiguration()
                DispatchQueue.global(qos: .background).async {
                    self.session!.startRunning()
                }
            }catch{
                print(error)
            }
            
        }
    }
    
    @objc
    func saveBtnClick(){
        self.customView.endEditing(true)
        //检查是否已签名
        if !self.customView.signView.signaturedFlag {
            Tool().showAlertViewWithOneBtn(message: R.string.localizable.pleaseSignBeforeSaving())
            return
        }
        
        let signedName = self.customView.signedTextfield.textField.text ?? ""
        //owner except individual
        if self.model.owner_address.type.lowercased() != "individual" && signatureType == .Owner && signedName == "" {
            self.customView.signedTextfield.defaultTipMsg = R.string.localizable.pleaseTypeOwnerSName()
            self.customView.signedTextfield.checkTextIfValid()
            return
        }
        //witness
        if signatureType == .Witness && signedName == "" {
            self.customView.signedTextfield.defaultTipMsg = R.string.localizable.pleaseTypeWitnessSName()
            self.customView.signedTextfield.checkTextIfValid()
            return
        }
        
        if self.signatureType == .Installer || self.signatureType == .Owner{
            if let _ = self.output,let _ = self.session {
                let settings = AVCapturePhotoSettings()
                output!.capturePhoto(with: settings, delegate: self)
            }else{
               self.saveSignature()
            }
            
        }else{
            self.saveSignature()
        }

    }
    //MARK: - APPConfig.loginInfo.signatureInfoModel用于提交签名（和信息以一样）；signatureModel用户增加本地数据（此VC只适用于老协议的签名）
    func saveSignature(_ selfieData: Data? = nil){
        guard let _ = self.model else {
            return
        }
            
        let image = self.customView.signView.getSignature()
        
        if let imageData = image.pngData() {
            self.customView.saveBtn.disableBtn()//此处是防止多次点击saveBtn，重复提交签名导致错误提示（NEWGD-914）
            //signatureModel，用于增加本地数据
            let signedAt = DateUtil().getCurrentDatetime()
            let signatureModel = SignatureImageDBModel()
            signatureModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            APPConfig.loginInfo.signatureInfoModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            //签名图片
            signatureModel.image_data = NSData(data: imageData)
            signatureModel.signed_at = signedAt
            signatureModel.signature_type = self.signatureType
            APPConfig.loginInfo.currentSignatureType = self.signatureType
            //
            switch signatureType {
            case .Installer:
                //签名数据
                APPConfig.loginInfo.signatureInfoModel.installer_sign_imagedata = NSData(data: imageData)
                APPConfig.loginInfo.signatureInfoModel.installer_signed_at = signedAt
                //经纬度
                if let latitude = Double(APPConfig.currentLocation.latitude), let longitude = Double(APPConfig.currentLocation.longitude){
                    signatureModel.installer_signature_latitude = latitude
                    signatureModel.installer_signature_longitude = longitude
                }
                APPConfig.loginInfo.signatureInfoModel.installer_signature_latitude = APPConfig.currentLocation.latitude
                APPConfig.loginInfo.signatureInfoModel.installer_signature_longitude = APPConfig.currentLocation.longitude
                //协议自拍 selfi
                if let data = self.installerTermsSelfiData {
                    let originImageData = MediaUtil().resetSizeOfImageData(source_image: UIImage(data: data),maxSize: 100)
                    signatureModel.installer_agree_selfie = originImageData
                    APPConfig.loginInfo.signatureInfoModel.installer_agree_selfie = originImageData
                }
                
                //签名自拍
                if let data = selfieData{
                    let signSelfiData = MediaUtil().normalizedImage(data)
                    let originImageData = MediaUtil().resetSizeOfImageData(source_image: UIImage(data: signSelfiData),maxSize: 100)
                    signatureModel.installer_signature_selfie = originImageData
                    APPConfig.loginInfo.signatureInfoModel.installer_signature_selfie = originImageData
                }
                
            case .Designer:
                //签名数据
                APPConfig.loginInfo.signatureInfoModel.designer_sign_imagedata = NSData(data: imageData)
                APPConfig.loginInfo.signatureInfoModel.designer_signed_at = signedAt
                
            case .Owner:
                //签名数据
                APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata = NSData(data: imageData)
                APPConfig.loginInfo.signatureInfoModel.owner_signed_at = signedAt
                
                if self.model.is_aho {
                    signatureModel.owner_mandatory_declaration_version = "1"
                }else{
                    signatureModel.owner_mandatory_declaration_version = "2"
                }

                if model.owner_address.type.lowercased() == "individual" {//individual
                    signatureModel.print_name = self.model!.signatures.owner_full_name
                    APPConfig.loginInfo.signatureInfoModel.owner_signed_name = self.model!.signatures.owner_full_name
                }else if let printName = self.customView.signedTextfield.textField.text , printName != "" {//非individual
                    signatureModel.print_name = printName
                    APPConfig.loginInfo.signatureInfoModel.owner_signed_name = printName
                }
                //sign selfie
                if let data = selfieData {
                    let signSelfiData = MediaUtil().normalizedImage(data)
                    let originImageData = MediaUtil().resetSizeOfImageData(source_image: UIImage(data: signSelfiData),maxSize: 100)
                    signatureModel.owner_signature_selfie = originImageData
                    APPConfig.loginInfo.signatureInfoModel.owner_signature_selfie = originImageData
                }
                //获取协议中的交互参数
                if let data = APPConfig.loginInfo.signatureInfoModel.onlineStatementParams["physically_attended"] as? String {
                    signatureModel.physically_attended = data
                }
                //
                if self.model!.is_aus_solar_co {
                    signatureModel.owner_aussolarco_satisfactory_version = "1"
                    signatureModel.owner_satisfaction_completion_version = "1"
                }
            case .Witness:
                //签名数据
                APPConfig.loginInfo.signatureInfoModel.witness_sign_imagedata = NSData(data: imageData)
                APPConfig.loginInfo.signatureInfoModel.witness_signed_at = signedAt
                
                let printName = self.customView.signedTextfield.textField.text ?? ""
                if printName != "" {
                    signatureModel.print_name = printName
                    APPConfig.loginInfo.signatureInfoModel.witness_signed_name =  printName
                }
            default: break
                
            }
            //老协议要保存本地信息
            DBManager.shared.insertSignatureData(model: signatureModel)
            
            //上传签名
            InstallationSignatureService().setDataInfo(self).requestUploadSignature() { [weak self] in
                guard let strongSelf = self else { return  }
                InstallationSignatureService().setDataInfo(strongSelf).dealLocalSignatureByWitnessSave()//删除本地数据
                InstallationSignatureService().setDataInfo(strongSelf).backToDetailVC()
            } faildClosure: {  (code, errMsg) in
                Tool().showErrorInfo(code,errMsg)
            }
            
        }else{
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.signatures.signature.save.faild", comment: ""))
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let _ = self.session {
            self.session!.stopRunning()
        }
        //尽可能释放无用的内存
        self.session = nil
        self.output = nil
        self.installerTermsSelfiData = nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }

}
extension PVDSignagtureViewController: AVCapturePhotoCaptureDelegate,UITextFieldDelegate{
    //UITextFieldDelegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let _ = self.session{
            self.session!.stopRunning()
        }
        
        if let _ = error{
            let errMsg = "\(self.signatureType.rawValue) sign and can not take selfi, the reason: " + error!.localizedDescription
            AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
            self.saveSignature()
        }else{
            if let imageData = photo.fileDataRepresentation() {
                self.saveSignature(imageData)
            }else{
                let errMsg = "\(self.signatureType.rawValue) sign and can not take selfi, the reason: photo.fileDataRepresentation() not working"
                AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
                self.saveSignature()
            }
        }
    }
}
